package edu.swust.graduation_project.eauction.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.PopupWindow
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException
import edu.swust.graduation_project.eauction.R
import java.sql.DriverManager
import java.sql.SQLException


class LoginActivity : AppCompatActivity() {

    //定义加载弹窗样式，加载时使用Handler来启用
    val popupWindow = PopupWindow()
    val handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            popupWindow.height = ViewGroup.LayoutParams.WRAP_CONTENT
            popupWindow.width = ViewGroup.LayoutParams.WRAP_CONTENT
            popupWindow.isFocusable = true
            val view: View =
                LayoutInflater.from(this@LoginActivity).inflate(R.layout.layout_popupwindow, null)
            popupWindow.contentView = view
            when (msg.what) {
                1 -> popupWindow.showAtLocation(window.decorView, Gravity.CENTER, 0, 0)
                2 -> {
                    popupWindow.dismiss()
                    Log.d("popupWindow", "2")
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        //定义view控件
        val mBtnSign = findViewById<Button>(R.id.btn_sign_in)
        val mBtnLogin = findViewById<Button>(R.id.btn_login)
        val mEtUsername = findViewById<EditText>(R.id.et_username)
        val mEtPassword = findViewById<EditText>(R.id.et_password)

        //点击注册按钮跳转到SignInActivity(注册界面)
        mBtnSign.setOnClickListener {
            startActivity(Intent(this, SignInActivity::class.java))
        }

        //点击登录按钮调用Handler并尝试查询MySQL获取并验证账号信息
        mBtnLogin.setOnClickListener {
            //由于Android不能在主线程中请求网络，所以所有的使用MySQL的操作都要另开线程
            object : Thread() {
                override fun run() {
                    Looper.prepare()
                    val message = Message()
                    message.what = 1
                    handler.sendMessage(message)
                    loginMysql() //尝试登录数据库
                }
            }.start()
        }
    }

    //登录数据库
    private fun loginMysql() {
        val mEtUsername = findViewById<EditText>(R.id.et_username).text.toString().trim()
        val mEtPassword = findViewById<EditText>(R.id.et_password).text.toString().trim()
        val sqlSelect = "SELECT * FROM `Account` WHERE " + //使用查询语句获取用户名和密码
                "`user_name` = '$mEtUsername' " +
                "AND `password` = '$mEtPassword'"
        //尝试连接数据库
        try {
            Class.forName("com.mysql.jdbc.Driver") //加载驱动
            val cn = DriverManager.getConnection( //建立连接至腾讯云服务器，访问’test_case‘数据库
                "*",
                "*", "*"
            )
            val ps = cn.createStatement()//创建对象用以执行SQL语句
            val resultSet = ps!!.executeQuery(sqlSelect)//执行sqlSelect语句，返回查询结果

            //判断resultSet中是否存在符合用户名称和密码的结果
            if (!resultSet.next()) {
                //登陆失败，数据库中找不到该用户名或密码，调用Handler关闭加载
                val message = Message()
                message.what = 2
                handler.sendMessage(message)
                //Looper.prepare()
                Toast.makeText(this@LoginActivity, "登录数据库失败，请检查用户名或密码", Toast.LENGTH_SHORT).show()
            } else {
                //登陆成功
                Toast.makeText(this@LoginActivity, "登录数据库成功", Toast.LENGTH_SHORT).show()
                val mSharedPreferences: SharedPreferences = getSharedPreferences(
                    "user",
                    MODE_PRIVATE
                )
                val mEditor: SharedPreferences.Editor = mSharedPreferences.edit()
                mEditor.putString("username", mEtUsername)
                mEditor.putString("password", mEtPassword)
                mEditor.apply()
                Toast.makeText(this@LoginActivity, "登录服务器成功", Toast.LENGTH_SHORT).show()
                //登录完成，跳转至ContainerActivity(应用界面)，关闭LoginActivity
                startActivity(Intent(this@LoginActivity, ContainerActivity::class.java))
                finish()
                while (resultSet.next()) {
                    Log.d(
                        "mysqlConnection: ",
                        resultSet.getString("user_name") +
                                resultSet.getString("isroot") +
                                resultSet.getString("password") +
                                resultSet.getString("user_email") +
                                resultSet.getString("user_phone")
                    )
                }
                //关闭
                ps.close()
                cn?.close()
            }
        } catch (e: ClassNotFoundException) {
            Looper.prepare()
            Toast.makeText(this@LoginActivity, "$e", Toast.LENGTH_SHORT).show()
            Looper.loop()
            e.printStackTrace()
        } catch (e: SQLException) {
            Looper.prepare()
            Toast.makeText(this@LoginActivity, "$e", Toast.LENGTH_SHORT).show()
            Looper.loop()
            e.printStackTrace()
        } catch (e: MySQLNonTransientConnectionException) {
            val message = Message()
            message.what = 2
            handler.sendMessage(message)
            Looper.prepare()
            Toast.makeText(this@LoginActivity, "创立链接失败", Toast.LENGTH_SHORT).show()
            Looper.loop()
            e.printStackTrace()
        }
    }
}